import 'package:fluent_ui/fluent_ui.dart';
import 'package:flutter/material.dart' show Icons;
import 'package:fnos_tv_desktop/core/api/bean/media_info_result.dart';
import 'package:provider/provider.dart';
import 'package:rxdart/rxdart.dart';

import '../../core/api/api.dart';
import '../../core/model/categories.dart';
import '../../core/model/media_databases.dart';
import 'home/home_view.dart';

class MainPageModel {
  final navigatorKey = GlobalKey<NavigatorState>();
  late final MediaDatabases databases;
  late final Categories categories;

  late final homeItem = PaneItem(
    key: const ValueKey('/'),
    icon: Icon(FluentIcons.home),
    body: const SizedBox.shrink(),
    title: Text('首页'),
    onTap: () {
      navigatorKey.currentState?.pushNamedAndRemoveUntil('/', (r) => false);
    },
  );
  final _selectedIndex = BehaviorSubject.seeded(0);

  Stream<int> get selectedIndexStream => _selectedIndex.stream;

  late final _items = BehaviorSubject<List<NavigationPaneItem>>.seeded([
    homeItem,
  ]);

  Stream<List<NavigationPaneItem>> get items => _items.stream;

  int get selectedIndex => _selectedIndex.value;

  set selectedIndex(int value) {
    if (value != selectedIndex) {
      _selectedIndex.value = value;
      switch (value) {
        case 0:
          navigatorKey.currentState?.pushNamedAndRemoveUntil('/', (r) => false);
          break;
        case 1:
          navigatorKey.currentState?.pushNamedAndRemoveUntil(
            '/favor',
            (r) => false,
          );
          break;
        default:
          if (value > 1 && value < libItems.length + 2) {
            navigatorKey.currentState?.pushNamedAndRemoveUntil(
              '/media_db',
              (r) => false,
              arguments: databases.databases![value - 2],
            );
          } else {
            final i = value - libItems.length - 2;
            switch (i) {
              case 0:
                navigatorKey.currentState?.pushNamedAndRemoveUntil(
                  '/category',
                  (r) => false,
                  arguments: 'all',
                );
                break;
              case 1:
                navigatorKey.currentState?.pushNamedAndRemoveUntil(
                  '/category',
                  (r) => false,
                  arguments: 'tv',
                );
                break;
              case 2:
                navigatorKey.currentState?.pushNamedAndRemoveUntil(
                  '/category',
                  (r) => false,
                  arguments: 'movie',
                );
                break;
              case 3:
                navigatorKey.currentState?.pushNamedAndRemoveUntil(
                  '/category',
                  (r) => false,
                  arguments: 'other',
                );
                break;
              default:
                break;
            }
          }
      }
    }
  }

  String get title {
    final index = selectedIndex;
    switch (index) {
      case 0:
        return '首页';
      case 1:
        return '收藏';
      default:
        if (index > 1 && index < libItems.length + 2) {
          return databases.databases![index - 2].title.toString();
        } else {
          final i = index - libItems.length - 2;
          switch (i) {
            case 0:
              return '全部';
            case 1:
              return '电视节目';
            case 2:
              return '电影';
            case 3:
              return '其他';
            default:
              return '';
          }
        }
    }
  }

  PaneItem? favorItem;
  var libItems = <NavigationPaneItem>[];
  var categoryItems = <NavigationPaneItem>[];

  final _playList = BehaviorSubject<List<MediaInfoResult>>.seeded([]);

  Stream<List<MediaInfoResult>> get playList => _playList.stream;

  void init(BuildContext context) {
    databases = context.read<MediaDatabases>();
    databases.addListener(_onMediaDatabaseChanged);
    categories = context.read<Categories>();
    categories.addListener(_onCategoriesChanged);
  }

  void dispose() {
    databases.removeListener(_onMediaDatabaseChanged);
    categories.removeListener(_onCategoriesChanged);
    _selectedIndex.close();
    _items.close();
  }

  void refresh() async {
    final api = Api();
    final mediaDatabases = await api.getMediaDatabases();
    final mediaDbSum = await api.getMediaDbSum();
    databases.update(mediaDatabases, mediaDbSum);
    categories.update(mediaDbSum);

    final playList = await api.getPlayList();
    _playList.value = playList;
  }

  void _updateItems() {
    final items = <NavigationPaneItem>[
      homeItem,
      ?favorItem,
      if (libItems.isNotEmpty) PaneItemHeader(header: Text('媒体库')),
      ...libItems,
      PaneItemHeader(header: Text('分类')),
      ...categoryItems,
    ];
    ;
    if (selectedIndex > libItems.length + 5) {
      _selectedIndex.value = 0;
    }
    _items.value = items;
  }

  void _onMediaDatabaseChanged() {
    final dbs = databases.databases;
    libItems =
        dbs?.map((e) {
          return PaneItem(
            key: ValueKey(e.guid),
            icon: Icon(_getIconByCategory(e.category)),
            body: const SizedBox.shrink(),
            title: Text(e.title),
            trailing: Padding(
              padding: const EdgeInsets.all(8.0),
              child: Text('${e.sum}'),
            ),
            onTap: () {
              navigatorKey.currentState?.pushNamedAndRemoveUntil(
                '/media_db',
                (r) => false,
                arguments: e,
              );
            },
          );
        }).toList() ??
        [];
    _updateItems();
  }

  IconData _getIconByCategory(String category) {
    switch (category) {
      case 'TV':
        return Icons.tv;
      case 'Movie':
        return Icons.movie;
      case 'Others':
        return Icons.folder;
      default:
        return Icons.menu;
    }
  }

  void _onCategoriesChanged() {
    favorItem = PaneItem(
      key: const ValueKey('/favor'),
      icon: Icon(FluentIcons.heart),
      body: const SizedBox.shrink(),
      title: Text('收藏'),
      trailing: Padding(
        padding: const EdgeInsets.all(8.0),
        child: Text('${categories.favorite}'),
      ),
      onTap: () {
        navigatorKey.currentState?.pushNamedAndRemoveUntil(
          '/favor',
          (r) => false,
        );
      },
    );
    categoryItems = [
      PaneItem(
        key: const ValueKey('/all'),
        icon: Icon(Icons.menu),
        body: const SizedBox.shrink(),
        title: Text('全部'),
        trailing: Padding(
          padding: const EdgeInsets.all(8.0),
          child: Text('${categories.total}'),
        ),
        onTap: () {
          navigatorKey.currentState?.pushNamedAndRemoveUntil(
            '/category',
            (r) => false,
            arguments: 'all',
          );
        },
      ),
      PaneItem(
        key: const ValueKey('/tv'),
        icon: Icon(Icons.tv),
        body: const SizedBox.shrink(),
        title: Text('电视节目'),
        trailing: Padding(
          padding: const EdgeInsets.all(8.0),
          child: Text('${categories.tv}'),
        ),
        onTap: () {
          navigatorKey.currentState?.pushNamedAndRemoveUntil(
            '/category',
            (r) => false,
            arguments: 'tv',
          );
        },
      ),
      PaneItem(
        key: const ValueKey('/movie'),
        icon: Icon(Icons.movie),
        body: const SizedBox.shrink(),
        title: Text('电影'),
        trailing: Padding(
          padding: const EdgeInsets.all(8.0),
          child: Text('${categories.movie}'),
        ),
        onTap: () {
          navigatorKey.currentState?.pushNamedAndRemoveUntil(
            '/category',
            (r) => false,
            arguments: 'movie',
          );
        },
      ),
      PaneItem(
        key: const ValueKey('/other'),
        icon: Icon(Icons.folder),
        body: const SizedBox.shrink(),
        title: Text('其他'),
        trailing: Padding(
          padding: const EdgeInsets.all(8.0),
          child: Text('${categories.video}'),
        ),
        onTap: () {
          navigatorKey.currentState?.pushNamedAndRemoveUntil(
            '/category',
            (r) => false,
            arguments: 'other',
          );
        },
      ),
    ];
    _updateItems();
  }

  void goToMediaDb(MediaDatabase db) {
    selectedIndex = databases.databases!.indexOf(db) + 2;
  }

  void goToDetails(MediaInfoResult info) {
    String path;
    switch (info.type) {
      case 'Movie':
        path = '/movie';
        break;
      case 'TV':
        path = '/tv';
        //todo 有两种，一种是显示多个季的列表，一种是显示多个集次的列表
        break;
      case 'Episode':
        path = '/episode';
        //todo 显示单集次的详情，和电影类似
      default:
        path = '/404';
    }
    navigatorKey.currentState?.pushNamedAndRemoveUntil(
      path,
      (r) => false,
      arguments: info,
    );
  }
}
